<template>
  <Drawer class="w-full max-w-[800px]" :title="state.getDrawerTitle">
    <!-- <ATabs v-model:activeKey="state.activeKey">
      <ATabPane :tab="$t('system.user.basicInfo')" key="1">
        <Form class="mx-4" :layout="isHorizontal ? 'horizontal' : 'vertical'">
          <template #addSubOrg="slotProps">
            <div class="flex items-center">
              <AButton type="primary" ghost @click="addExtOrgRow" class="mb-2">
                {{ $t('system.user.addSubOrg') }}
              </AButton>
              <span
                style="
                  font-size: 12px;
                  color: gray;
                  padding-left: 5px;
                  white-space: nowrap;
                "
                >{{ $t('system.user.subOrgHelp') }}</span
              >
            </div>
          </template>
        </Form>
      </ATabPane>
    </ATabs> -->

    <ATabs v-model:activeKey="state.activeKey">
      <ATabPane :tab="$t('system.user.basicInfo')" key="1">
        <AForm
          ref="formRef"
          :model="state.formState"
          :rules="state.rules"
          :label-col="{ span: 24 }"
        >
          <ARow :gutter="16">
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.account')" name="account">
                <AInput v-model:value="state.formState.account" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.nickName')" name="nickName">
                <AInput v-model:value="state.formState.nickName" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.phone')" name="phone">
                <AInput v-model:value="state.formState.phone" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.realName')" name="realName">
                <AInput v-model:value="state.formState.realName" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.accountType')"
                name="accountType"
              >
                <ASelect
                  v-model:value="state.formState.accountType"
                  :options="state.accountTypeOptions"
                  :allowClear="true"
                  :showSearch="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.email')" name="email">
                <AInput v-model:value="state.formState.email" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.orderNo')" name="orderNo">
                <AInputNumber
                  v-model:value="state.formState.orderNo"
                  defaultValue="100"
                  :min="1"
                  class="w-full"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.status')" name="status">
                <ARadioGroup
                  v-model:value="state.formState.status"
                  :options="[
                    { label: $t('common.enabled'), value: 1 },
                    { label: $t('common.disabled'), value: 2 },
                  ]"
                  buttonStyle="solid"
                  optionType="button"
                />
              </AFormItem>
            </ACol>
          </ARow>
          <ADivider dashed>
            {{ $t('system.user.org') }}
          </ADivider>
          <ARow :gutter="16">
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.belongOrg')" name="orgId">
                <ATreeSelect
                  v-model:value="state.formState.orgId"
                  :tree-data="state.orgData"
                  :treeDefaultExpandAll="true"
                  treeNodeFilterProp="name"
                  :allowClear="true"
                  :showSearch="true"
                  :fieldNames="{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.pos')" name="posId">
                <ASelect
                  v-model:value="state.formState.posId"
                  :options="state.posData"
                  :allowClear="true"
                  :showSearch="true"
                  :fieldNames="{ label: 'name', value: 'id' }"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.jobNum')" name="jobNum">
                <AInput v-model:value="state.formState.jobNum" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.domainAccount')"
                name="domainAccount"
              >
                <AInput v-model:value="state.formState.domainAccount" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.joinDate')" name="joinDate">
                <ADatePicker
                  v-model:value="state.formState.joinDate"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </AFormItem>
            </ACol>
          </ARow>

          <ADivider dashed>
            {{ $t('system.user.subOrg') }}
          </ADivider>
          <ARow :gutter="16">
            <ACol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <AButton type="primary" ghost @click="addExtOrgRow" class="mb-2">
                {{ $t('system.user.addSubOrg') }}
              </AButton>
              <span
                style="
                  font-size: 12px;
                  color: gray;
                  padding-left: 5px;
                  white-space: nowrap;
                "
                >{{ $t('system.user.subOrgHelp') }}</span
              >
            </ACol>
            <ACol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div
                v-if="
                  state.formState.extOrgIdList != undefined &&
                  state.formState.extOrgIdList?.length > 0
                "
              >
                <ARow
                  :gutter="16"
                  v-for="(item, index) in state.formState.extOrgIdList"
                  class="flex items-center"
                >
                  <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                    <AFormItem
                      :label="$t('system.user.org')"
                      :name="['extOrgIdList', index, 'orgId']"
                      :rules="{
                        required: true,
                        trigger: 'change',
                      }"
                    >
                      <ATreeSelect
                        v-model:value="
                          state.formState.extOrgIdList[index].orgId
                        "
                        :tree-data="state.orgData"
                        :treeDefaultExpandAll="true"
                        treeNodeFilterProp="name"
                        :allowClear="true"
                        :showSearch="true"
                        :fieldNames="{
                          label: 'name',
                          value: 'id',
                          children: 'children',
                        }"
                      />
                    </AFormItem>
                  </ACol>
                  <ACol :xs="22" :sm="10" :md="8" :lg="8" :xl="8">
                    <AFormItem
                      :label="$t('system.user.pos')"
                      :name="['extOrgIdList', index, 'posId']"
                      :rules="{
                        required: true,
                        trigger: 'change',
                      }"
                    >
                      <ASelect
                        v-model:value="
                          state.formState.extOrgIdList[index].posId
                        "
                        :options="state.posData"
                        :allowClear="true"
                        :showSearch="true"
                        :fieldNames="{ label: 'name', value: 'id' }"
                      />
                    </AFormItem>
                  </ACol>
                  <ACol :xs="2" :sm="2" :md="8" :lg="8" :xl="8">
                    <IconifyIcon
                      icon="carbon:close-outline"
                      class="mt-4 size-4 cursor-pointer"
                      @click="deleteExtOrgRow(index)"
                    />
                  </ACol>
                </ARow>
              </div>
              <AEmpty v-else />
            </ACol>
          </ARow>
        </AForm>
      </ATabPane>
      <ATabPane :tab="$t('system.user.roleAuth')" key="2">
        <ATransfer
          :titles="[
            $t('system.user.unauthorized'),
            $t('system.user.authorized'),
          ]"
          :dataSource="state.roleData"
          v-model:selectedKeys="state.formState.selectedRoleKeys"
          v-model:targetKeys="state.formState.roleIdList"
          :rowKey="(item) => item.id"
          :render="(item) => item.name"
        />
      </ATabPane>
      <ATabPane :tab="$t('system.user.archiveInfo')" key="3">
        <AForm
          ref="formRef"
          :model="state.formState"
          :rules="state.rules"
          :label-col="{ span: 24 }"
        >
          <ARow :gutter="16">
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.cardType')" name="cardType">
                <ASelect
                  v-model:value="state.formState.cardType"
                  :options="getDictTypeOptions('CardTypeEnum')"
                  :allowClear="true"
                  :showSearch="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.idCardNum')" name="idCardNum">
                <AInput v-model:value="state.formState.idCardNum" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.birthday')" name="birthday">
                <ADatePicker
                  v-model:value="state.formState.birthday"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.sex')" name="sex">
                <ARadioGroup
                  v-model:value="state.formState.sex"
                  :options="getDictTypeOptions('GenderEnum')"
                  buttonStyle="solid"
                  @change="handleSexChange"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.age')" name="age">
                <AInputNumber
                  v-model:value="state.formState.age"
                  defaultValue="18"
                  :min="18"
                  :max="100"
                  class="w-full"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.nation')" name="nation">
                <ASelect
                  v-model:value="state.formState.nation"
                  :options="getDictTypeOptions('NationEnum')"
                  :allowClear="true"
                  :showSearch="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <AFormItem
                :label="$t('system.user.address')"
                name="address"
                class="col-span-2"
              >
                <ATextarea
                  v-model:value="state.formState.address"
                  showCount
                  :maxlength="256"
                  :allowClear="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem :label="$t('system.user.college')" name="college">
                <AInput v-model:value="state.formState.college" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.cultureLevel')"
                name="cultureLevel"
              >
                <ASelect
                  v-model:value="state.formState.cultureLevel"
                  :options="getDictTypeOptions('CultureLevelEnum')"
                  :allowClear="true"
                  :showSearch="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.politicalOutlook')"
                name="politicalOutlook"
              >
                <AInput v-model:value="state.formState.politicalOutlook" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.officePhone')"
                name="officePhone"
              >
                <AInput v-model:value="state.formState.officePhone" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.emergencyContact')"
                name="emergencyContact"
              >
                <AInput v-model:value="state.formState.emergencyContact" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <AFormItem
                :label="$t('system.user.emergencyPhone')"
                name="emergencyPhone"
              >
                <AInput v-model:value="state.formState.emergencyPhone" />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <AFormItem
                :label="$t('system.user.emergencyAddress')"
                name="emergencyAddress"
              >
                <ATextarea
                  v-model:value="state.formState.emergencyAddress"
                  showCount
                  :maxlength="256"
                  :allowClear="true"
                />
              </AFormItem>
            </ACol>
            <ACol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <AFormItem :label="$t('system.user.remark')" name="remark">
                <ATextarea
                  v-model:value="state.formState.remark"
                  showCount
                  :maxlength="256"
                  :allowClear="true"
                />
              </AFormItem>
            </ACol>
          </ARow>
        </AForm>
      </ATabPane>
    </ATabs>
  </Drawer>
</template>

<script lang="ts" setup>
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core';
import { useVbenDrawer, VbenTree } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { useVbenForm } from '#/adapter/form';

import { $t } from '#/locales';

import { useFormSchema } from '../data';
const handleSexChange = (value: any) => {
  console.log(value);
};
const breakpoints = useBreakpoints(breakpointsTailwind);
const isHorizontal = computed(() => breakpoints.greaterOrEqual('md').value);
const formRef = ref();
const state = reactive({
  getDrawerTitle: computed(() => {
    return state.formState?.id
      ? $t('common.edit', $t('system.role.name'))
      : $t('common.create', $t('system.role.name'));
  }),
  formState: {
    status: 1,
  } as UpdateUserInput,
  rules: {
    account: [{ required: true, trigger: 'change' }],
    nickName: [{ required: true, trigger: 'change' }],
    phone: [{ required: true, trigger: 'change' }],
    realName: [{ required: true, trigger: 'change' }],
    accountType: [{ required: true, trigger: 'change' }],
    status: [{ required: true, trigger: 'change' }],
    orgId: [{ required: true, trigger: 'change' }],
    posId: [{ required: true, trigger: 'change' }],
  },
  activeKey: '1',
  accountTypeOptions: [],
  orgData: [],
  roleData: [],
}) as any;

const emits = defineEmits(['success']);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    colon: false,
    // formItemClass: 'col-span-1',
  },
  schema: useFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});

// const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    try {
      const valid = await formRef.value.validate();
    } catch (err) {
      return;
    }
    // if (!valid) return;
    // console.log("asdf")

    // const { valid1 } = await formApi.validate();
    // console.log(valid1);
    // const values = await formApi.getValues();
    drawerApi.lock();
    (state.formState.id
      ? updateUser(state.formState)
      : addUser(state.formState)
    )
      .then(() => {
        emits('success');
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      formRef.value?.resetFields();
      //请求组织和岗位数据
      const [orgList, posList, roleList] = await Promise.all([
        getOrgList(),
        getPosList(),
        getRoleList(),
      ]);

      state.roleData = roleList;
      state.accountTypeOptions = getDictTypeOptions('AccountTypeEnum').filter(
        (item: any) => item.code !== 'SuperAdmin',
      );

      const data = drawerApi.getData<UpdateUserInput>();
      if (data.id) {
        // 获取用户扩展机构和用户拥有角色集合
        const [extOrgList, roleIdList] = await Promise.all([
          getOwnExtOrgList(data.id),
          getOwnRoleList(data.id),
        ]);

        state.formState = data;
        state.formState.extOrgIdList = extOrgList;
        state.formState.roleIdList = roleIdList;
        state.formState.orgId = data.orgId === 0 ? undefined : data.orgId;
        state.formState.posId = data.posId === 0 ? undefined : data.posId;
      }

      //如果有租户id，则过滤组织和岗位数据
      if (data?.tenantId) {
        state.orgData = orgList.filter(
          (item: any) => item.tenantId === data.tenantId,
        );
        state.posData = posList.filter(
          (item: any) => item.tenantId === data.tenantId,
        );
      } else {
        state.orgData = orgList;
        state.posData = posList;
      }
    }
  },
});

/** 增加附属机构 */
const addExtOrgRow = () => {
  if (state.formState.extOrgIdList == undefined) {
    state.formState.extOrgIdList = [];
  }
  state.formState.extOrgIdList.push({});
};

/** 删除附属机构 */
const deleteExtOrgRow = (index: number) => {
  state.formState.extOrgIdList?.splice(index, 1);
};
</script>
